package com.zm.se.controller;

import com.zm.se.entity.Manager;
import com.zm.se.mapper.managerMapper.ManagerMapper;
import com.zm.se.service.managerService.IManagerService;
import com.zm.se.util.EmailSend;
import com.zm.se.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/users")
public class ManagerController extends BaseController{
    @Resource
    IManagerService managerService;

    @Autowired
    ManagerMapper manager;



    //登录
    @RequestMapping("/logininfo")
    public JsonResult<Void> logininfo(HttpSession session){
       session.removeAttribute("num");
        return  new JsonResult<>(OK);
    }


    @Autowired
    EmailSend emailSend;

   private String realKey="";
   //获取验证码
    @RequestMapping("/sendRegKey")
    public JsonResult<String> sendVerificationCode(String num){
        System.out.println(num);
        realKey= emailSend.KeyCreated();
        if (emailSend.RegisterManager(realKey,managerService.findRegPwd(num))==1){
          return new JsonResult<>(OK);
        }
        return new JsonResult<>(1000,"发送失败，请重试");
    }
    //注册
    //http//localhost:8080/users/register?username=zm&password=1234
    @RequestMapping("/register")
    public JsonResult<String> register(Manager manager,String key){
        System.out.println("key"+key);
        System.out.println("realkey"+realKey);
        if (key.equals(realKey)){
            System.out.println("==");
           managerService.reg(manager);
            System.out.println("success");
            return new JsonResult<>(OK);
        }else {
            System.out.println("false");
            return new JsonResult<>(1111);
        }

    }
    @RequestMapping("/loginnum")
    public JsonResult<String> loginnum( HttpSession session){
        String managernum=getNumFromSession(session);
        System.err.println(managernum);
        return new JsonResult<>(OK,managernum);
    }


    private String VerificationCode="";
    @RequestMapping("/sendFindPwd")
    public JsonResult<String> sendFindPwd(String num){
        System.out.println(num);
        VerificationCode=emailSend.KeyCreated();
        System.out.println(VerificationCode);
            if (emailSend.RegisterManager(VerificationCode,managerService.findPwd(num))==1){
                return new JsonResult<>(OK);
            }
        return new JsonResult<>(1000,"发送失败，请重试");
    }
    @RequestMapping("/backPwd")
    public JsonResult<String> findPwd(String num,String key){
        System.out.println("key:"+key);
        System.out.println("VerificationCode:"+VerificationCode);
        if (!VerificationCode.equals(key)){
            return new JsonResult<>(1111,"验证码错误");
        }
        return new JsonResult<>(OK);
    }

    @RequestMapping("/resetPwd")
    public JsonResult<String> resetPwd(String num,String password){
        if (managerService.resetPwd(num,password)!=1){
            return new JsonResult<>(11111,"重置失败，请重试");
        }
        return new JsonResult<>(OK);

    }
    //登录
    @RequestMapping("/login")
    public JsonResult<String> login(String num, String password, HttpSession session){

        Manager manager=managerService.login(num,password);
        session.setAttribute("mid",manager.getMid());
        session.setAttribute("num",manager.getNum());
        String managernum=getNumFromSession(session);
        System.err.println(managernum);
        return new JsonResult<>(OK,managernum);
    }
    @RequestMapping("/showupdate")
    public JsonResult<Manager> showupdate(HttpSession session){
        Manager info=manager.findByNum(getNumFromSession(session));
        return new JsonResult<>(OK,info);
    }

    //修改信息（密码，手机号）
    @RequestMapping("/updateInfo")
    public JsonResult<Void> updatePassword(String oldPassword,String newPassword,String phone,String email,HttpSession session){
        String num=getNumFromSession(session);
        managerService.changeInfo(oldPassword,newPassword,num,phone,email);
        return new JsonResult<>(OK);

    }

    @GetMapping("showinfo")
    public JsonResult<Manager> showEmp(HttpSession session){
        return new JsonResult<>(OK,manager.findByNum(getNumFromSession(session)));
    }
    @GetMapping("/delManager")
    public JsonResult<Manager> delManager(Integer num){
        if (num!=null) {
            if (manager.delManager(num) != 1) {
                return new JsonResult<>(50001);
            } else {
                return new JsonResult<>(OK);
            }
        }else {
            return new JsonResult<>(50001);
        }
    }


    /*显示所有员工信息*/
    @RequestMapping("showallemp")
    public JsonResult<List> showAllEmp(){
        return new JsonResult<List>(OK,manager.findAllEmp());
    }

    @PostMapping("uploademp")
    public JsonResult<String> uploadEmp(
            @RequestParam("file") MultipartFile file, HttpSession session) {
        // 日志
        System.err.println("UserController.changeAvatar()");

        // 判断文件是否为空
        boolean isEmpty = file.isEmpty();
        System.err.println("\tisEmpty=" + isEmpty);
        if (isEmpty) {
            System.out.println("empty");
        }


        // 获取原始文件名(客户端设备中的文件名)
        String originalFilename
                = file.getOriginalFilename();
        System.err.println("\toriginalFilename=" + originalFilename);

        // 将文件上传到哪个文件夹
        String parent = session
                .getServletContext().getRealPath("upload");
        System.err.println("\tupload path=" + parent);
        File dir = new File(parent);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 保存上传的文件时使用的文件名
        String filename = ""
                + System.currentTimeMillis()
                + System.nanoTime();
        String suffix = "";
        int beginIndex = originalFilename
                .lastIndexOf(".");
        if (beginIndex >= 1) {
            suffix = originalFilename
                    .substring(beginIndex);
        }
        String child = filename + suffix;

        // 将客户端上传的文件保存到服务器端
        File dest = new File(parent, child);
        try {
            file.transferTo(dest);
        } catch (IllegalStateException e) {
            System.out.println(
                    "上传失败！您的文件的状态异常！");
        } catch (IOException e) {
            System.out.println(
                    "上传失败！读写文件时出现错误，请重新上传！");
        }

        // 将保存的文件的路径记录到数据库中
        String avatar = "\\" + child;
        System.err.println("\tavatar path=" + avatar);
        System.out.println();
        System.out.println(managerService.ExcelRead(parent,avatar));
        return new JsonResult<>(OK);
    }




}
